package org.cl.persist.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.cl.persist.system.data.fo.BaseFo;
import org.springboot.gls.ex.utils.String.TuoLuoFengTools;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashSet;

/**
 * @author cl
 */
public class QueryWrapperPlus<T> extends QueryWrapper<T> {

    /**
     * 扩展条件查询
     * @param entity 查询条件 需要和数据库字段对应
     * @param excludeFileName 忽略字段
     * @param <O> 查询条件限制
     * @return
     */
    public <O extends BaseFo> QueryWrapper<T> selectPage(O entity, String... excludeFileName) {
        // 获取请求实体类的所有字段 不包括父类的
        Field[] fields = entity.getClass().getDeclaredFields();
        HashSet<String> efname = new HashSet<>();
        if (excludeFileName != null && excludeFileName.length > 0) {
            efname.addAll(Arrays.asList(excludeFileName));
        }
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                // 获取字段名称
                String fieldName = field.getName();
                // 获取指定对象的当前字段的值
                Object val = field.get(entity);
                Class<?> type = field.getType();
                if (val == null || efname.contains(fieldName)) {
                    continue;
                }
                // 转下划线
                final String columnName = TuoLuoFengTools.humpToLine2(fieldName);
                if (type == String.class && ((String)val).length() < 32) {
                    this.and(w -> w.like(columnName, val));
                } else {
                    this.and(w -> w.eq(columnName, val));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return this;
    }
}
